import { NextResponse } from 'next/server';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';
import jwt from 'jsonwebtoken';

/**
 * 删除需求API
 * DELETE /api/enterprise/resources/needs/[id]
 * 需要登录且为企业管理员
 */
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const id = params.id;
    
    // 1. 验证用户是否已登录
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 2. 解析token
    const token = authHeader.substring(7); // 去掉"Bearer "前缀
    const secret = process.env.JWT_SECRET || 'your-secret-key';
    
    let decodedToken;
    try {
      decodedToken = jwt.verify(token, secret);
    } catch (error) {
      return NextResponse.json(
        { success: false, message: '无效的令牌' },
        { status: 401 }
      );
    }

    // 3. 获取用户信息
    const userId = (decodedToken as any).id;
    
    // 4. 查询用户是否为企业管理员
    const userQuery = `
      SELECT u.id, u.is_company_admin, c.id as company_id
      FROM users u 
      LEFT JOIN companies c ON u.id = c.admin_id
      WHERE u.id = ?
    `;
    const [userResult] = await query<RowDataPacket[]>(userQuery, [userId]);
    
    if (!userResult || !userResult.is_company_admin) {
      return NextResponse.json(
        { success: false, message: '只有企业管理员才能删除需求' },
        { status: 403 }
      );
    }
    
    // 5. 查询需求是否存在且属于该企业
    const needQuery = `
      SELECT id, company_id FROM enterprise_cooperation_needs
      WHERE id = ?
    `;
    const [needResult] = await query<RowDataPacket[]>(needQuery, [id]);
    
    if (!needResult) {
      return NextResponse.json(
        { success: false, message: '需求不存在' },
        { status: 404 }
      );
    }
    
    if (needResult.company_id !== userResult.company_id) {
      return NextResponse.json(
        { success: false, message: '您没有权限删除此需求' },
        { status: 403 }
      );
    }
    
    // 6. 删除需求
    const deleteQuery = `DELETE FROM enterprise_cooperation_needs WHERE id = ?`;
    await query(deleteQuery, [id]);
    
    return NextResponse.json({
      success: true,
      message: '需求已成功删除'
    });
  } catch (error) {
    console.error('删除需求失败:', error);
    return NextResponse.json(
      { success: false, message: '删除需求失败' },
      { status: 500 }
    );
  }
} 